import os
import glob
import logging
from config.settings import LOCAL_INFLUENCER_PATH  # 需要在config.py中添加该配置

logger = logging.getLogger(__name__)


def read_local_influencer_resources() -> dict:
    """读取本地达人主页资源（txt和webp）"""
    result = {"document": "", "image_urls": []}

    if not os.path.exists(LOCAL_INFLUENCER_PATH):
        logger.warning(f"本地达人目录不存在: {LOCAL_INFLUENCER_PATH}")
        return result

    # 读取TXT文件
    txt_files = glob.glob(os.path.join(LOCAL_INFLUENCER_PATH, "*.txt"))
    for txt_file in txt_files:
        try:
            with open(txt_file, 'r', encoding='utf-8') as f:
                result["document"] += f"\n\n【{os.path.basename(txt_file)}】\n{f.read()}"
        except Exception as e:
            logger.warning(f"读取TXT失败: {txt_file}, {str(e)}")

    # 读取图片
    webp_files = glob.glob(os.path.join(LOCAL_INFLUENCER_PATH, "*.webp"))
    result["image_urls"] = [
        f"file:///{path.replace(os.sep, '/')}" for path in webp_files
    ]

    if not result["document"] and not result["image_urls"]:
        logger.warning(f"本地达人目录无内容: {LOCAL_INFLUENCER_PATH}")

    return result


def ensure_dir_exists(path: str):
    """确保目录存在"""
    if not os.path.exists(path):
        os.makedirs(path, exist_ok=True)
